import datetime
import json
import time
import pyautogui
import os
import GetPort
import binFile

class downloader:
    def __init__(self):
        self.cf = None
        self.target_value =None
        self.target_value_otp = None
        self.target_value_otp2 = None
        self.error_value = None
        self.rizhiFile = "D:/Desktop/haawking_downloader_1.2.16.beta7/log.log"
        self.name = None
        self.item = None
        self.gpt = GetPort.GetPort()
        self.comName = GetPort.GetPort().getCOMPort("CH340")
        self.txt = None

    def choose(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(url+"无法找到文件夹窗口")
            self.choose(url)
        folder_window_center = pyautogui.center(folder_window_position)
        pyautogui.moveTo(folder_window_center, duration=1)
        pyautogui.click()
        time.sleep(1)
    def find(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(url+"无法找到文件夹窗口")
            self.find(url)
        folder_window_center = pyautogui.center(folder_window_position)
        return folder_window_center

    # 选择芯片型号
    def xpxh(self):
        xinpxh = self.find("./image/XPXH.png")
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y)
        time.sleep(1)
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y + self.item.get("xpxh_y"))

        time.sleep(1)
    # 选择芯片版本号
    def banbenhao(self):
        banbenhao = self.find("./image/BBH.png")
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y)
        time.sleep(1)
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y + self.item.get("bbh_y"))
        time.sleep(1)

    # 选择芯片连接方式
    def lianjiefangshi(self):
        ljfs = self.find("./image/LJFS.png")
        pyautogui.click(x=ljfs.x + 50, y=ljfs.y)
        time.sleep(1)
        pyautogui.click(y=ljfs.y + self.item.get("ljfs_sci_y"))
        time.sleep(1)
    # 选择连接端口
    def lianjieduankou(self):
        ljduankou = self.find("./image/LJDK.png")
        pyautogui.click(x=ljduankou.x + 50, y=ljduankou.y)
        time.sleep(1)
        pyautogui.click(y=ljduankou.y + 30)
        time.sleep(1)
    # 点击选择输入文件路径位置
    def filelocat(self):
        locat = self.find("./image/open.png")
        pyautogui.click(x=locat.x + 60, y=locat.y + 15)
        time.sleep(1)
    # 选择芯片和型号
    def caozuo(self):
        # print(xpxh_y,bbh_y)
        time.sleep(2)
        self.xpxh()
        self.banbenhao()
        self.lianjiefangshi()
        self.choose("./image/refresh.png")
        self.lianjieduankou()

    # 选择文件并打开
    def chooseFile_Open(self,file):
        # 选择文件
        self.choose('./image/chooseFile.png')
        time.sleep(1)
        # 点击文件路径
        self.filelocat()
        # 写文件路径
        pyautogui.typewrite(folder_path)
        time.sleep(1)
        # 之后回车
        pyautogui.press('enter')
        # 点击文件名输入框
        self.choose('./image/name.png')
        # 输入文件名
        pyautogui.typewrite(file)
        # 选择打开
        self.choose('./image/openfile.png')
        time.sleep(1)
    # 擦除Flash
    def erase_flash(self):
        pyautogui.click(self.find("./image/erase_flash.png"))
    # 空片检查
    def kpjiancha(self):
        pyautogui.click(self.find("./image/Empty_Check.png"))
    # 载入Flash
    def down_flash(self):
        pyautogui.click(self.find("./image/down_flash.png"))
    # 对比校验和
    def bijiaoJYH(self):
        pyautogui.click(self.find("./image/Compare_Checksum.png"))
        time.sleep(1)

    def File_Down(self):
        with open(f'{self.rizhiFile}', 'r') as log_path_file:
            i = 1
            while (i):
                content = log_path_file.read()
                if "FLASH编程完成!" in content:
                    self.txt = 'success '
                    i = 0
                    time.sleep(5)
                    self.gpt.jtag_port(self.comName, self.item.get("jtag"))
                elif "执行失败! 请检查所选芯片型号、设备模式是否正确，密码是否正确，复位键是否按下，然后请按下复位键后重试!" in content:
                    self.txt = 'Failure! '
                    i = 0
                    time.sleep(0.5)
                    self.gpt.jtag_port(self.comName, self.item.get("jtag"))
    def File(self,file):
        log_path = f'{self.rizhiFile}'
        # 文件下载完成
        self.target_JYH = "结果"
        self.error_value = "执行失败! 请检查所选芯片型号、设备模式是否正确，密码是否正确，复位键是否按下，然后请按下复位键后重试!"
        i = 1
        # 打开日志文件
        with open(log_path, 'r') as log_path_file:
            while (i):
                content = log_path_file.read()
                # print(content,"content")
                # 日志文件有结果两个字或执行失败，跳出循环
                if self.target_JYH in content:
                    print(content)
                    # self.txt = content[27:31] + "OTP:" + content[33:38] +"Flash:"+ content[53:57]
                    self.txt = 'success '
                    i = 0
                    time.sleep(0.5)
                    self.gpt.jtag_port(self.comName, self.item.get("jtag"))
                    with open("result_down_success.txt", "a", encoding='utf-8') as result_down_success:
                        result_down_success.write(f'success:{self.txt}  {self.cf}  {self.name},  {file},  {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} "\n')
                elif self.error_value in content:
                    self.txt = '执行失败! '
                    i = 0
                    time.sleep(0.5)
                    self.gpt.jtag_port(self.comName, self.item.get("jtag"))


    def list_files_in_folder(self,folder_path):
        try:
            # 获取文件夹中的所有文件
            files = os.listdir(folder_path)
            print(files)
            for file in files:
                # 拼接文件夹路径和文件名
                file_path = os.path.join(folder_path, file)
                # 判断是否为文件
                if os.path.isfile(file_path):
                    # 选择芯片型号、版本号、连接方式、连接端口
                    self.caozuo()
                    # 选择文件一系列操作
                    self.chooseFile_Open(file)
                    #选择的hex文件是否存在重复地址的数据
                    # self.chongfu('./image/chongfu.png')
                    time.sleep(1)
                    pyautogui.press('enter')
                    time.sleep(15)
                    self.erase_flash()
                    time.sleep(1)
                    self.kpjiancha()
                    time.sleep(1)
                    self.down_flash()
                    time.sleep(1)
                    self.bijiaoJYH()
                    time.sleep(1)

                    # 勾选完成点击执行
                    self.choose('./image/Perform.png')
                    # 遍历日志文件，找到“编程完成”跳出循环，继续执行
                    self.File_Down()


                    time.sleep(2)
                    pyautogui.press('enter')
                    time.sleep(2)
                    # 将结果存放到日志文件result.txt
                    with open("result.txt", "a",encoding='utf-8') as result:
                        result.write(f'{self.name},  {file},  {self.txt} {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
        except FileNotFoundError:
            print("找不到指定的文件夹:", folder_path)


if __name__ == "__main__":
    downloader = downloader()
    current_time = datetime.time
    print(current_time)
    dataInfo = None
    comName = downloader.gpt.getCOMPort("CH340")
    data = json.load(open('sci_json.json', 'r', encoding='utf-8'))
    for item in data:
        downloader.name = item.get("name")
        downloader.item = item
        jtag = item.get("jtag")
        print(jtag)
        time.sleep(1)
        downloader.gpt.jtag_port(comName,jtag)
        time.sleep(1)
        folder_path = f'D:/hx_downloader_tool/downloader/case/{downloader.name}'
        downloader.list_files_in_folder(folder_path)
